<template>
  <div class="space-y-4">
    <!-- 地址选择标题 -->
    <div class="flex items-center justify-between">
      <h3 class="text-lg font-medium text-gray-900">收货地址</h3>
      <button
        @click="openAddressForm"
        class="inline-flex items-center px-3 py-2 text-sm font-medium text-gray-900 bg-gray-50 border border-gray-200 rounded-md hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors"
      >
        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
        </svg>
        添加新地址
      </button>
    </div>

    <!-- 地址列表 -->
    <div v-if="addresses.length > 0" class="space-y-3">
      <div
        v-for="address in sortedAddresses"
        :key="address.id"
        class="relative border-2 rounded-lg p-4 cursor-pointer transition-all duration-200 hover:shadow-md"
        :class="selectedAddressId === address.id 
          ? 'border-gray-900 bg-gray-50 shadow-md' 
          : 'border-gray-200 hover:border-gray-300'"
        @click="selectAddress(address)"
      >
        <div class="flex items-start justify-between">
          <div class="flex-1 min-w-0">
            <!-- 地址头部信息 -->
            <div class="flex items-center space-x-2 mb-2">
              <span class="font-medium text-gray-900 truncate">{{ address.name }}</span>
              <span class="text-gray-500 text-sm">{{ address.phone }}</span>
              <div class="flex space-x-1">
                <span v-if="address.is_default" class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                  默认
                </span>
                <span v-if="address.label" class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                  {{ address.label }}
                </span>
              </div>
            </div>
            
            <!-- 地址详情 -->
            <p class="text-sm text-gray-600 leading-relaxed">
              {{ address.province }} {{ address.city }} {{ address.district }} {{ address.address }}
            </p>
            
            <!-- 邮政编码 -->
            <p v-if="address.postal_code" class="text-xs text-gray-500 mt-1">
              邮编：{{ address.postal_code }}
            </p>
          </div>
          
          <!-- 选中状态指示器 -->
          <div v-if="selectedAddressId === address.id" class="ml-4 flex-shrink-0">
            <div class="w-6 h-6 bg-gray-900 rounded-full flex items-center justify-center">
              <svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
              </svg>
            </div>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="flex items-center justify-end space-x-2 mt-3 pt-3 border-t border-gray-100">
          <button
            @click.stop="editAddress(address)"
            class="inline-flex items-center px-2 py-1 text-xs font-medium text-gray-600 hover:text-gray-900 hover:bg-gray-50 rounded transition-colors"
          >
            <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
            </svg>
            编辑
          </button>
          <button
            @click.stop="confirmDeleteAddress(address)"
            class="inline-flex items-center px-2 py-1 text-xs font-medium text-gray-600 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
          >
            <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
            删除
          </button>
        </div>
      </div>
    </div>

    <!-- 无地址提示 -->
    <div v-else class="text-center py-12">
      <div class="mx-auto w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
        <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
        </svg>
      </div>
      <h3 class="text-lg font-medium text-gray-900 mb-2">暂无收货地址</h3>
      <p class="text-sm text-gray-500 mb-6">请添加收货地址以便完成订单</p>
      <button
        @click="openAddressForm"
        class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors"
      >
        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
        </svg>
        添加地址
      </button>
    </div>

    <!-- 地址表单弹窗 -->
    <div v-if="showAddressForm" class="fixed inset-0 z-50 overflow-y-auto">
      <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <!-- 背景遮罩 -->
        <div 
          class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" 
          @click="closeAddressForm"
        ></div>

        <!-- 弹窗内容 -->
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full">
          <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <div class="sm:flex sm:items-start">
              <div class="w-full">
                <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">
                  {{ editingAddress ? '编辑收货地址' : '添加新地址' }}
                </h3>
                <AddressForm
                  :address="editingAddress"
                  :provinces="provinces"
                  @cancel="closeAddressForm"
                  @address-saved="handleAddressSaved"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteConfirm" class="fixed inset-0 z-50 overflow-y-auto">
      <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <!-- 背景遮罩 -->
        <div 
          class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" 
          @click="showDeleteConfirm = false"
        ></div>

        <!-- 确认弹窗 -->
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
          <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <div class="sm:flex sm:items-start">
              <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                <svg class="h-6 w-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                </svg>
              </div>
              <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                <h3 class="text-lg leading-6 font-medium text-gray-900">
                  确认删除地址
                </h3>
                <div class="mt-2">
                  <p class="text-sm text-gray-500">
                    您确定要删除此收货地址吗？此操作不可撤销。
                  </p>
                </div>
              </div>
            </div>
          </div>
          <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
            <button
              @click="deleteAddress"
              class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm"
            >
              删除
            </button>
            <button
              @click="showDeleteConfirm = false"
              class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
            >
              取消
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { router } from '@inertiajs/vue3'
import { useNotification } from '@/composables/useNotification'
import AddressForm from './AddressForm.vue'

// 定义组件选项
defineOptions({
  name: 'AddressSelector',
  inheritAttrs: false
})

// 定义 Props 和 Emits
const props = defineProps({
  addresses: {
    type: Array,
    default: () => []
  },
  selectedAddressId: {
    type: [Number, String],
    default: null
  },
  provinces: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:selectedAddressId', 'address-selected'])

const { showSuccess, showError } = useNotification()

// 响应式数据
const showAddressForm = ref(false)
const editingAddress = ref(null)
const showDeleteConfirm = ref(false)
const addressToDelete = ref(null)

// 排序后的地址列表：默认地址优先，然后按最后使用时间排序
const sortedAddresses = computed(() => {
  return [...props.addresses].sort((a, b) => {
    // 默认地址优先
    if (a.is_default && !b.is_default) return -1
    if (!a.is_default && b.is_default) return 1
    
    // 按最后使用时间排序
    const dateA = a.last_used_at ? new Date(a.last_used_at) : new Date(a.created_at)
    const dateB = b.last_used_at ? new Date(b.last_used_at) : new Date(b.created_at)
    return dateB.getTime() - dateA.getTime()
  })
})

// 选择地址
const selectAddress = (address) => {
  emit('update:selectedAddressId', address.id)
  emit('address-selected', address)
  
  // 更新最后使用时间
  if (address.id) {
    router.post(route('addresses.set-last-used', address.id), {}, {
      preserveScroll: true,
      preserveState: true,
      onSuccess: () => {
        // 刷新地址列表以显示更新的最后使用时间
        router.reload({ only: ['addresses'] })
      }
    })
  }
}

// 打开地址表单
const openAddressForm = () => {
  editingAddress.value = null
  showAddressForm.value = true
}

// 编辑地址
const editAddress = (address) => {
  editingAddress.value = { ...address }
  showAddressForm.value = true
}

// 关闭地址表单
const closeAddressForm = () => {
  showAddressForm.value = false
  editingAddress.value = null
}

// 地址保存成功
const handleAddressSaved = () => {
  closeAddressForm()
  showSuccess('地址保存成功', '')
  
  // 刷新地址列表
  router.reload({ only: ['addresses'] })
}

// 确认删除地址
const confirmDeleteAddress = (address) => {
  addressToDelete.value = address
  showDeleteConfirm.value = true
}

// 删除地址
const deleteAddress = async () => {
  if (!addressToDelete.value) return

  try {
    await router.delete(route('addresses.destroy', addressToDelete.value.id), {
      onSuccess: () => {
        showSuccess('地址删除成功', '')
        showDeleteConfirm.value = false
        addressToDelete.value = null
        
        // 如果删除的是当前选中的地址，清空选择
        if (props.selectedAddressId === addressToDelete.value.id) {
          emit('update:selectedAddressId', null)
        }
        
        // 刷新地址列表
        router.reload({ only: ['addresses'] })
      },
      onError: () => {
        showError('删除失败', '请重试')
      }
    })
  } catch (error) {
    showError('删除失败', '请重试')
  }
}

// 组件挂载时，如果没有选中地址且有默认地址，自动选中默认地址
onMounted(() => {
  if (!props.selectedAddressId && props.addresses.length > 0) {
    const defaultAddress = props.addresses.find(addr => addr.is_default)
    if (defaultAddress) {
      selectAddress(defaultAddress)
    } else {
      // 如果没有默认地址，选择第一个
      selectAddress(props.addresses[0])
    }
  }
})
</script>